﻿<%@ WebHandler Language="C#" Class="AHMHRIRSF06" %>

using System;
using System.Web;
using System.Linq;
using System.Collections.Generic;
using System.Configuration;

public class AHMHRIRSF06 : IHttpHandler
{
    string vappid = "AHMIC";
    string vformid = "AHMIC_AHMHRIRSF06";

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "application/json";
        AjaxResponse axresp = new AjaxResponse();
        string user = AHMIDEAFunctions.ContextUser(context);

        // Field Names
        string f_filter_tema = "filter_teamrole";
        string f_action = "action";
        string f_page = "page";

        // Field values
        string v_filtertype = AHMIDEAFunctions.ContextGetData(context, f_filter_tema);
        string v_action = AHMIDEAFunctions.ContextPostData(context, f_action);
        int v_page = 1;
        int.TryParse(AHMIDEAFunctions.ContextPostData(context, f_page), out v_page);
        if (v_page <= 0) v_page = 1;

        // if get table list (default request if action is empty)
        if (string.IsNullOrEmpty(v_action) || (v_action.ToLower() == "goto_page") || (v_action.ToLower() == "sort") || (v_action.ToLower() == "filter"))
        {
            context.Response.ContentType = "text/html";
            context.Response.Write(generateListData(context,v_page,v_filtertype));
        }
        else {
            switch (v_action.ToLower())
            {
                case "add":
                    axresp = InsertData(context);
                    break;
                case "edit":
                    axresp = UpdateData(context);
                    break;
                case "delete":
                    axresp = DeleteData(context);
                    break;
                default:
                    break;
            }
            context.Response.Write(axresp.GenerateJSON());
        }
        
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

    AjaxResponse DeleteData(HttpContext context)
    {
        AjaxResponse resp = new AjaxResponse();

        // Field Names
        string f_vteamroleid = "vteamroleid";
        string f_vteamroledesc = "vteamroledesc";

        // Field values
        string[] v_vteamrole = AHMIDEAFunctions.ContextPostDataCollection(context, f_vteamroleid);
        string v_vteamroledesc = AHMIDEAFunctions.ContextPostData(context, f_vteamroledesc);

        try
        {
            using (DC_AHMHRIRSDataContext dc = new DC_AHMHRIRSDataContext())
            {
                var d = (from t in dc.AHMHRIRS_MEMROLEs where  v_vteamrole.Contains(t.VROLEID) select t);
                if (d != null)
                {

                    dc.AHMHRIRS_MEMROLEs.DeleteAllOnSubmit(d);
                    dc.SubmitChanges();

                    resp.Status = "1";
                    resp.Message = "Data successfully deleted.";
                }
                else
                {
                    resp.Status = "0";
                    resp.Message = "No data found.";
                }
            }
        }
        catch (Exception ex)
        {
            resp.Status = "0";
            resp.Message = ex.Message;
        }

        return resp;
    }

    AjaxResponse UpdateData(HttpContext context)
    {
        AjaxResponse resp = new AjaxResponse();

        // Field Names
        string f_vteamroleid = "vteamroleid";
        string f_vteamroledesc = "vteamroledesc";
        string f_istatus = "istatus";

        // Field values
        string v_vteamrole = AHMIDEAFunctions.ContextPostData(context, f_vteamroleid);
        string v_vteamroledesc = AHMIDEAFunctions.ContextPostData(context, f_vteamroledesc);
        int v_istatus = 0;
        int.TryParse(AHMIDEAFunctions.ContextPostData(context, f_istatus), out v_istatus);

        // validations
        FormValidation validation = new FormValidation();
        validation.RegisterField(f_vteamroleid, "Team Role ID", v_vteamrole, "Required,LimitLength", 10);
        validation.RegisterField(f_vteamroledesc, "Deskripsi Team Role", v_vteamroledesc, "Required,LimitLength", 50);
        validation.RegisterField(f_istatus, "Status", v_istatus.ToString(), "Required");
        validation.ValidateFields();

        if (validation.IsValid)
        {
            try
            {
                using (DC_AHMHRIRSDataContext dc = new DC_AHMHRIRSDataContext())
                {
                    var d = (from t in dc.AHMHRIRS_MEMROLEs where t.VROLEID == v_vteamrole select t).FirstOrDefault();
                    if (d != null)
                    {
                        d.VNAME = v_vteamroledesc;
                        d.ISTATUS = (short)v_istatus;
                        dc.SubmitChanges();

                        resp.Status = "1";
                        resp.Message = "Data successfully updated.";
                    }
                    else
                    {
                        resp.Status = "0";
                        resp.Message = "No data found.";
                    }
                }
            }
            catch (Exception ex)
            {
                resp.Status = "0";
                resp.Message = ex.Message;
            }
        }
        else
        {
            resp.Status = "0";
            resp.ErrorFields = validation.GetErrorMessages(true);
        }

        return resp;
    }

    AjaxResponse InsertData(HttpContext context)
    { 
        AjaxResponse resp = new AjaxResponse();

        // Field Names
        string f_vteamroleid = "vteamroleid";
        string f_vteamroledesc = "vteamroledesc";
        string f_istatus = "istatus";

        // Field values
        string v_vteamrole = AHMIDEAFunctions.ContextPostData(context, f_vteamroleid);
        string v_vteamroledesc = AHMIDEAFunctions.ContextPostData(context, f_vteamroledesc);
        int v_istatus = 0;
        int.TryParse(AHMIDEAFunctions.ContextPostData(context, f_istatus), out v_istatus);

        // validations
        FormValidation validation = new FormValidation();
        validation.RegisterField(f_vteamroleid, "Tipe ID", v_vteamrole, "Required,LimitLength", 10);
        validation.RegisterField(f_vteamroledesc, "Deskripsi Tipe", v_vteamroledesc, "Required,LimitLength", 50);
        validation.RegisterField(f_istatus, "Status", v_istatus.ToString(), "Required");
        validation.ValidateFields();

        if (validation.IsValid)
        {
            try
            {
                using (DC_AHMHRIRSDataContext dc = new DC_AHMHRIRSDataContext())
                {
                    AHMHRIRS_MEMROLE tblType = new AHMHRIRS_MEMROLE();
                    tblType.VROLEID = v_vteamrole;
                    tblType.VNAME= v_vteamroledesc;
                    tblType.ISTATUS = (short)v_istatus;

                    dc.AHMHRIRS_MEMROLEs.InsertOnSubmit(tblType);
                    dc.SubmitChanges();

                    resp.Status = "1";
                    resp.Message = "Data successfully inserted.";
                }
            }
            catch (Exception ex) {
                resp.Status = "0";
                resp.Message = ex.Message;
            }
        }
        else {
            resp.Status = "0";
            resp.ErrorFields = validation.GetErrorMessages(true);
        }
        
        return resp;
    }
    
    string generateListData(HttpContext context, int v_page, string filtertype)
    {

        // Set default values
        int maxDisplayed = int.Parse(ConfigurationManager.AppSettings["_CONFIG_MAX_DISPLAYED_ROWS"]);
        int totalData = 0;
        
        // get sort data
        string vsortby = AHMIDEAFunctions.ContextGetData(context, "sortby");
        string vsortdir = AHMIDEAFunctions.ContextGetData(context, "sortdir");

        // Define Table Fields
        List<ResponsiveTableField> fields = new List<ResponsiveTableField>();
        fields.Add(new ResponsiveTableField
        {
            FieldTitle = "Team Role ID",
            FieldName = "vteamroleid",
            Priority = ResponsiveTableField.DisplayPriority.Priority2,
            Width = "15%",
            Sortable = true
        });
        fields.Add(new ResponsiveTableField
        {
            FieldTitle = "Deskripsi",
            FieldName = "vteamroledesc",
            Priority = ResponsiveTableField.DisplayPriority.Priority1,
            IsMainField = true,
            Sortable = true
        });
        fields.Add(new ResponsiveTableField
        {
            FieldTitle = "Status",
            FieldName = "istatus",
            Priority = ResponsiveTableField.DisplayPriority.Priority3,
            Width = "15%",
            Sortable = true
        });

        // Generate Defult Data
        List<ResponsiveTableRow> tblData = new List<ResponsiveTableRow>();
        ResponsiveTableRow _row;
        List<ResponsiveTableItem> _items;
        using (DC_AHMHRIRSDataContext dc = new DC_AHMHRIRSDataContext())
        {
            var tematypes = (from t in dc.AHMHRIRS_MEMROLEs select t);
            // check filter
            if (!string.IsNullOrEmpty(filtertype))
            {
                tematypes = tematypes.Where(t => t.VROLEID.ToLower().Contains(filtertype) || t.VNAME.ToLower().Contains(filtertype));
            }
            // check order
            if (!string.IsNullOrEmpty(vsortby)) {
                if (!string.IsNullOrEmpty(vsortdir) && (vsortdir == "asc"))
                {
                    switch (vsortby)
                    {
                        case "vteamroleid":
                            tematypes = tematypes.OrderBy(i => i.VROLEID);
                            break;
                        case "vteamroledesc":
                            tematypes = tematypes.OrderBy(i => i.VNAME);
                            break;
                        case "istatus" :
                            tematypes = tematypes.OrderBy(i => i.ISTATUS);
                            break;    
                    }
                    
                }
                else {
                    switch (vsortby)
                    {
                        case "vteamroleid":
                            tematypes = tematypes.OrderByDescending(i => i.VNAME);
                            break;
                        case "vteamroledesc":
                            tematypes = tematypes.OrderByDescending(i => i.VROLEID);
                            break;
                        case "istatus":
                            tematypes = tematypes.OrderByDescending(i => i.ISTATUS);
                            break;
                    }
                }
            }

            totalData = tematypes.Count();
            if ((int)Math.Ceiling((double)totalData / maxDisplayed) < v_page) v_page = 1;

            var queryResultPage = tematypes.Skip(maxDisplayed * (v_page - 1)).Take(maxDisplayed);
            foreach (var ttitem in queryResultPage)
            {
                _row = new ResponsiveTableRow();
                _items = new List<ResponsiveTableItem>();
                _items.Add(new ResponsiveTableItem { Key = "vteamroleid", Value = ttitem.VROLEID});
                _items.Add(new ResponsiveTableItem { Key = "vteamroledesc", Value = ttitem.VNAME});
                _items.Add(new ResponsiveTableItem { Key = "istatus", Value = (ttitem.ISTATUS==1? "Aktif": "Non Aktif") });
                _row.AddRow(_items);
                tblData.Add(_row);
            }
        }

        // Generate Table
        ResponsiveTable respTable = new ResponsiveTable(tblData);
        respTable.Fields = fields;
        respTable.Page = v_page;
        respTable.TotalData = totalData;
        if (!string.IsNullOrEmpty(vsortby)) respTable.SortBy = vsortby;
        if (!string.IsNullOrEmpty(vsortdir)) respTable.SortDirection = vsortdir == "desc" ? ResponsiveTable.Sort.Descending : ResponsiveTable.Sort.Ascending;

        if (AHMIDEAFunctions.IsFunctionAuthorized(HttpContext.Current, vappid, vformid,  "ADD")) respTable.AddAction = "ahmhrirsf06_new(this)";
        if (AHMIDEAFunctions.IsFunctionAuthorized(HttpContext.Current, vappid, vformid, "EDIT")) respTable.EditAction = "ahmhrirsf06_edit(this)";
        if (AHMIDEAFunctions.IsFunctionAuthorized(HttpContext.Current, vappid, vformid, "DELETE")) respTable.DeleteAction = "ahmhrirsf06_delete(this)";

        return respTable.RenderTable();
    }
}